package com.wdd.myplatform.controller.mqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wdd 2022/4/25
 */
@RestController
@RequestMapping("/mqtt")
public class MqttDemoController {

    @Value("${customer.mqtt.clientList[0].clientId}")
    private String clientId;

    @GetMapping("/pub")
    public void pub(@RequestParam("clientId") String clientId,@RequestParam("topic") String topic, @RequestParam("message") String message){
        if(StringUtils.isBlank(clientId)){
            clientId = this.clientId;
        }
        MqttClientUtil.sendMqttMsg(clientId,topic,message);
    }

    @GetMapping("/pubtest")
    public void pubtest(){
        if(StringUtils.isBlank(clientId)){
            clientId = this.clientId;
        }
        String topic = "/provision/request";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceName","device007");
        jsonObject.put("provisionDeviceKey","m4iacmbrxbfhb04tsd7z");
        jsonObject.put("provisionDeviceSecret","pu4whk6mjpgoj99xrz9z");

        String message = JSON.toJSONString(jsonObject);
        MqttClientUtil.sendMqttMsg(clientId,topic,message);
    }

    @GetMapping("/subscribe")
    public void subscribe(@RequestParam("clientId") String clientId,@RequestParam("topic") String topic) throws MqttException {
        if(StringUtils.isBlank(clientId)){
            clientId = this.clientId;
        }
        MqttClient mqttClient = MqttClientManager.getMqttClientById(clientId);
        mqttClient.subscribe(topic);
    }

}
